package com.example.summary.leetcode;

/**
 * Created by wzn on 2019/9/11.
 */
public class LeetCode2 {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(5);
        ListNode l2 = new ListNode(5);
        ListNode result = addTwoNumbers(l1, l2);

        while (null != result) {
            System.out.println(result.val);
            result = result.next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        return addTwoNumbers(l1, l2, 0);
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2, int x) {
        if (null == l1 && null == l2 && x == 0) {
            return null;
        }

        ListNode result = new ListNode(0);

        int num = (null != l1 ? l1.val : 0) + (null != l2 ? l2.val : 0) + x;
        x = 0;

        if (num >= 10) {
            x = 1;
            result.val = num - 10;
        } else {
            result.val = num;
        }

        result.next = addTwoNumbers(
                null != l1 ? l1.next : null,
                null != l2 ? l2.next : null,
                x);

        return result;
    }

    public static class ListNode {

        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
